import Vue from "vue";
import {isNullOrUndefined} from "../../lib/core";
import {Loading} from "element-ui";


export const requestList=[]

//新增一个模拟后端的返回数据
export function newResult({code=200,msg='操作成功',data}={}){
    return {
        code: code,
        msg: msg,
        data: data,
    }
}

/**
 *
 * @param path
 * @param timeout           接口请求等待时间
 * @param request
 * @param result
 */
export function addSuccessController({path,timeout=500,request,result}={}){
    let requestList = Vue.prototype.requestList;
    let requestTmp={
        timeout: timeout,
        path: path,
        request: undefined,
    }
    if (isNullOrUndefined(request)) {
        requestTmp.request=(config)=>{
            let data=newResult({
                data: result
            })
            return Promise.resolve(data)
        }
    }else{
        requestTmp.request=request
    }

    requestList.unshift(requestTmp)
}


/**
 *
 * @param config
 * @return {Promise}
 */
export function mockRequest(config={}){
    console.log("mockRequest.config",config)
    let loading
    let url=config.url
    //全局loading加载中
    const isLoading = config.isLoading?true:false
    if(isLoading){
        loading=Loading.service({
            lock: true,
            text: "拼命处理中",
            spinner: "el-icon-loading",
            background: "rgba(0, 0, 0, 0.7)",
        });
    }
    return new Promise((resolve,reject)=>{
        for (let tmp of Vue.prototype.requestList) {
            if (tmp.path == url) {
                setTimeout(()=>{
                    let result = tmp.request(config);
                    console.log("mockRequest.result",result)
                    resolve(result)
                },tmp.timeout||1)
                return
            }
        }
        reject(new Error("模拟请求数据未配置"))
    })
}

Vue.prototype.requestList=requestList
Vue.prototype.addSuccessController=addSuccessController
Vue.prototype.mockRequest=mockRequest
